package com.alibaba.boot.netty.groupChat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class GroupChatClient {

    private final String HOST="127.0.0.1";
    private final Integer  PORT = 6667;

    private Selector selector;

    private SocketChannel socketChannel;

    private String userName;


    public GroupChatClient() throws IOException{
        selector = selector.open();

        socketChannel = SocketChannel.open(new InetSocketAddress(HOST,PORT));

        socketChannel.configureBlocking(false);

        socketChannel.register(selector, SelectionKey.OP_READ);

        userName = socketChannel.getLocalAddress().toString().substring(1);

        System.out.println(userName+"is ok....");
    }

    public void  sendInfo(String info){

        info = userName+"said:"+info;

        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    public void readInfo(){

        try {

            int readChannels = selector.select();
            if (readChannels > 0){
              Iterator<SelectionKey> iterator =  selector.selectedKeys().iterator();

              while (iterator.hasNext()){

                 SelectionKey selectionKey= iterator.next();
                 if (selectionKey.isReadable()){
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    socketChannel.read(byteBuffer);
                    System.out.println("client readData:"+new String(byteBuffer.array()).trim());
                 }
                 else {
                     System.out.println("client did not have useable channel");
                 }
                  iterator.remove();
              }

            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {

        GroupChatClient groupChatClient = new GroupChatClient();


        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    groupChatClient.readInfo();
                    try {
                        Thread.sleep(1000);
                    }catch (Exception e){

                    }
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()){
            String s= scanner.nextLine();
            groupChatClient.sendInfo(s);
        }
    }
}
